﻿using Edu.Common.Extensions;
using Edu.Common.Logs;
using Edu.Common.Win32;
using System;
using System.Diagnostics;
using System.Windows;

namespace MainApp.Utils
{
    class Tools
    {
        private static readonly Lazy<ILogger> _lazyLogger;
        protected static ILogger Logger { get => _lazyLogger?.Value; }
        static Tools()
        {
            _lazyLogger = new Lazy<ILogger>(() => LogManager.GetLogger<Tools>(), System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);
        }
        /// <summary>
        /// 设置自动运行
        /// </summary>
        /// <param name="autoRun"></param>
        public static void SetAutoRun(bool? autoRun = null)
        {
            var isAutoRun = autoRun ?? AppConfig.Current.AutoRun;
            var appName = AppInfo.APP_NAME;
            var appStartupPath = AppInfo.APP_LOCATION;
            if (isAutoRun)
                AutoStartHelper.SetMeAutoStart(appName, appStartupPath, true);
            else
                AutoStartHelper.SetMeAutoStart(appName, appStartupPath, false);
        }
        /// <summary>
        /// 查找指定类型的窗口
        /// </summary>
        /// <typeparam name="TWindow"></typeparam>
        /// <returns></returns>
        public static TWindow FindWindow<TWindow>() where TWindow : Window
        {
            var widnows = Application.Current.Windows;
            for (var i = widnows.Count - 1; i >= 0; i--)
            {
                var window = widnows[i];
                if (window is TWindow win) return win;
            }
            return null;
        }
        /// <summary>
        /// 显示设置窗口
        /// </summary>
        public static void ShowSettingsWindow()
        {
            var settingsWindow = FindWindow<SettingsWindow>();
            if (settingsWindow != null)
            {
                settingsWindow.Activate();
                return;
            }
            settingsWindow = new SettingsWindow
            {
                Owner = Application.Current.MainWindow
            };
            settingsWindow.Show();
        }
        /// <summary>
        /// 启动文件
        /// </summary>
        /// <param name="file">要运行的文件</param>
        /// <param name="runasAdmin">是否以管理员身份运行</param>
        public static bool RunFile(string file, bool runasAdmin = false)
        {
            if (!file.FileExists()) return false;
            try
            {
                var startInfo = new ProcessStartInfo
                {
                    UseShellExecute = true,
                    FileName = file
                };
                if (runasAdmin)
                {
                    startInfo.Verb = "runas";
                }
                var process = Process.Start(startInfo);
                return process != null;
            }
            catch (Exception ex)
            {
                Logger.Error("", ex);
            }
            return false;
        }
        /// <summary>
        /// 执行命令
        /// </summary>
        /// <param name="str"></param>
        public static void Exec(string str)
        {
            try
            {
                using (Process process = new Process())
                {
                    process.StartInfo.FileName = "cmd.exe";//调用cmd.exe程序
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.RedirectStandardInput = true;//重定向标准输入
                    process.StartInfo.RedirectStandardOutput = true;//重定向标准输出
                    process.StartInfo.RedirectStandardError = true;//重定向标准出错
                    process.StartInfo.CreateNoWindow = true;//不显示黑窗口
                    process.Start();//开始调用执行
                    process.StandardInput.WriteLine(str + "&exit");//标准输入str + "&exit"，相等于在cmd黑窗口输入str + "&exit"
                    process.StandardInput.AutoFlush = true;//刷新缓冲流，执行缓冲区的命令，相当于输入命令之后回车执行
                    process.WaitForExit();//等待退出
                    process.Close();//关闭进程
                }
            }
            catch
            {
            }
        }
        /// <summary>
        /// 执行关机操作
        /// </summary>
        public static void Shutdown()
        {
            Exec("shutdown -s -f -t 0");
        }
        /// <summary>
        /// 前置窗体并让窗体取得焦点(如果窗口处于最小化状态则弹起窗体)
        /// </summary>
        /// <param name="hWnd"></param>
        public static void ForegroundWindow(IntPtr hWnd)
        {
            if (hWnd == IntPtr.Zero)
                return;
            if (User32.IsIconic(hWnd))
                User32.SwitchToThisWindow(hWnd, true);
            User32.SetForegroundWindow(hWnd);
            FocusWindow(hWnd);
        }
        /// <summary>
        /// 使置顶句柄的窗口获得焦点
        /// </summary>
        /// <param name="hWnd"></param>
        public static void FocusWindow(IntPtr hWnd)
        {
            if (hWnd == IntPtr.Zero)
                return;
            var WM_SETFOCUS = 0x0007;
            User32.PostMessage(hWnd, WM_SETFOCUS, 0, 0);
        }
        /// <summary>
        /// 选择ppt文件
        /// </summary>
        /// <returns></returns>
        public static string SelectPntFile()
        {
            var openFileDialog = new System.Windows.Forms.OpenFileDialog();
            openFileDialog.Filter = "PPT文件|*.ppt;*.pptx";
            var dialogResult = openFileDialog.ShowDialog();
            if (dialogResult != System.Windows.Forms.DialogResult.OK)
                return string.Empty;
            return openFileDialog.FileName;
        }
    }
}
